//
//  DataSource.m
//  lvtu
//
//  Created by Apple on 12-4-4.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "DataSource.h"
#import "SFHFKeychainUtils.h"
#import <CommonCrypto/CommonDigest.h>
#import "NSDate+Helper.h"
#include <sys/types.h>
#include <sys/sysctl.h>

@implementation DataSource
@synthesize userInfo;
@synthesize messageInfo;
@synthesize cityArray;
@synthesize cityDict;
@synthesize defaultCityInfo;
@synthesize creatTripInfo;
@synthesize editTripInfo;
@synthesize isEdit;
@synthesize isEditDataChanged;

static NSInteger DateSort(id s1, id s2, void *context)
{
    NSDate* date1 = [NSDate dateWithDateString:(NSString*)s1];
    NSTimeInterval time1 = [date1 timeIntervalSinceReferenceDate];
    NSDate* date2 = [NSDate dateWithDateString:(NSString*)s2];
    NSTimeInterval time2 = [date2 timeIntervalSinceReferenceDate];
    
    if (time1 > time2)
        return NSOrderedDescending;
    else if (time1 < time2)
        return NSOrderedAscending;
    else
        return NSOrderedSame;
}

+ (DataSource*)shareInstance
{
	static DataSource * instance = nil;
	if (instance == nil)
	{
		instance = [[DataSource alloc]init];
	}
	return instance;
}

- (void)initData
{
    userInfo = [[UserInfo alloc] init];
    messageInfo = [[MessageInfo alloc] init];
    currentDate = [[NSString alloc] init];
    editCurrentDate = [[NSString alloc] init];
    isEditDataChanged = NO;
    
    creatTripInfo = [[TripInfo alloc] init];
    editTripInfo = [[TripInfo alloc] init];
    cityDict = [[NSMutableDictionary alloc] init];
}

- (void)dealloc {
    [userInfo release];
    [messageInfo release];
    [currentDate release];
    [editCurrentDate release];
    
    [creatTripInfo release];
    [editTripInfo release];
    [cityDict release];
    [super dealloc];
}

//! 获取Cache的目录
- (NSString *)file_getAppCachePath
{
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return [paths objectAtIndex:0];
}
#pragma mark - 系统相关
- (NSString *)sys_getDeviceID
{
    UIDevice *device = [UIDevice currentDevice];
    NSString *deviceUID = [NSString stringWithString:[device uniqueIdentifier]];
    return deviceUID;
}

- (NSString *)sys_getOSVersion
{
    UIDevice *device = [UIDevice currentDevice];
    NSString *deviceUID = [NSString stringWithString:[device systemVersion]];
    return deviceUID;
}

- (NSString *)sys_getDeviceModelName
{
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
    free(machine);
    
    if ([platform isEqualToString:@"iPhone1,1"])
        return @"iPhone 1G";
    if ([platform isEqualToString:@"iPhone1,2"])
        return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"])
        return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPhone3,1"])
        return @"iPhone 4 (GSM)";
    if ([platform isEqualToString:@"iPhone3,2"])
        return @"iPhone 4 (CDMA)";
    if ([platform isEqualToString:@"iPod1,1"])
        return @"iPod Touch 1G";
    if ([platform isEqualToString:@"iPod2,1"])
        return @"iPod Touch 2G";
    if ([platform isEqualToString:@"iPod3,1"])
        return @"iPod Touch 3G";
    if ([platform isEqualToString:@"iPod4,1"])
        return @"iPod Touch 4G";
    if ([platform isEqualToString:@"iPad1,1"])
        return @"iPad";
    if ([platform isEqualToString:@"iPad2,1"])
        return @"iPad 2 (WiFi)";
    if ([platform isEqualToString:@"iPad2,2"])
        return @"iPad 2 (GSM)";
    if ([platform isEqualToString:@"iPad2,3"])
        return @"iPad 2 (CDMA)";
    if ([platform isEqualToString:@"i386"])
        return @"Simulator";
    
    return platform;
}

#pragma mark - 加解密相关
//! 将字符串转换为md5
- (NSString *)md5_hexDigest:(NSString *)input
{
    if (!input)
        return @"";
    const char *str = [input UTF8String];
    unsigned char result[16];
    CC_MD5(str, strlen(str), result);
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15]];
}

#pragma mark - 登录

//从钥匙链中取得用户的uid／gsid
- (LoginInfo*)getUserStatsFromKeyChain
{
    NSString *urlSchemeString = @"lv_wuxianlvtu";
    NSString *serviceName = [urlSchemeString stringByAppendingString:@"_userinfo"];
    
    NSString *userName = [SFHFKeychainUtils getPasswordForUsername:@"userName" andServiceName:serviceName error:nil];
    NSString *passWord = [SFHFKeychainUtils getPasswordForUsername:@"passWord" andServiceName:serviceName error:nil];
    
    LoginInfo* info = [[LoginInfo alloc] init];
    info.email = userName;
    info.password = passWord;
    
    return [info autorelease];
}

//把用户的uid／gsid存入钥匙链
- (void)saveUserStatusToKeyChain:(NSString *)userName passwd:(NSString *)passWord
{
    NSString *urlSchemeString = @"lv_wuxianlvtu";
    NSString *serviceName = [urlSchemeString stringByAppendingString:@"_userinfo"];
    [SFHFKeychainUtils storeUsername:@"userName" andPassword:userName forServiceName:serviceName updateExisting:YES error:nil];
    [SFHFKeychainUtils storeUsername:@"passWord" andPassword:passWord forServiceName:serviceName updateExisting:YES error:nil];
}

#pragma mark - data
- (NSString*)getCurrentDate
{
    if (isEdit) {
        return editCurrentDate;
    }
    return currentDate;
}

- (NSInteger)getDateCount
{
    if (isEdit) {
        return [editTripInfo.datedic count];
    }
    return [creatTripInfo.datedic count];
}

- (NSInteger)getTotleEventCount
{
    if (isEdit) {
        NSInteger count= 0;
        NSArray* keyArray = [editTripInfo.datedic allKeys];
        for (NSString* key in keyArray) {
            NSArray* array = [editTripInfo.datedic objectForKey:key];
            count += [array count];
        }
        return count;
    }
    NSInteger count= 0;
    NSArray* keyArray = [creatTripInfo.datedic allKeys];
    for (NSString* key in keyArray) {
        NSArray* array = [creatTripInfo.datedic objectForKey:key];
        count += [array count];
    }
    return count;
}

- (void)resetData
{
    if ([creatTripInfo.datedic count] > 0) {
        [creatTripInfo.datedic removeAllObjects];
    }
    [creatTripInfo release];creatTripInfo= nil;
    creatTripInfo = [[TripInfo alloc] init];
}

- (void)creatNextDate:(NSString*)date
{
    NSString* tempDate = [[NSString alloc] initWithString:date];
    if (isEdit) {
        NSMutableArray* dateArray = [[NSMutableArray alloc] init];
        if ([editTripInfo.datedic count] == 0) {
            editTripInfo.starttime = tempDate;
        }
        [editTripInfo.datedic setObject:dateArray forKey:tempDate];
        editTripInfo.endtime = tempDate;
        editCurrentDate = tempDate;
        return;
    }
    NSMutableArray* dateArray = [[NSMutableArray alloc] init];
    if ([creatTripInfo.datedic count] == 0) {
        creatTripInfo.starttime = tempDate;
    }
    [creatTripInfo.datedic setObject:dateArray forKey:tempDate];
    creatTripInfo.endtime = tempDate;
    currentDate = tempDate;
}

- (void)setDate:(NSString*)date
{
    NSString* tempDate = [[NSString alloc] initWithString:date];
    if (isEdit) {
        editCurrentDate = tempDate;
        return;
    }
    currentDate = tempDate;
}

- (NSString*)getDefaultCityId
{
    if (defaultCityInfo) {
        return defaultCityInfo.cityid;
    }
    return nil;
}

- (void)setCurrentCityinfo:(CityInfo*)Info
{
    self.defaultCityInfo = Info;
}

- (void)delCurrentEventAll
{
    if (isEdit) {
        NSMutableArray* eventArray = [editTripInfo.datedic objectForKey:editCurrentDate];
        [eventArray removeAllObjects];
        return;
    }
    NSMutableArray* eventArray = [creatTripInfo.datedic objectForKey:currentDate];
    [eventArray removeAllObjects];
}

- (NSMutableArray*)getCurrentEvent
{
    if (isEdit) {
        NSMutableArray* eventArray = [editTripInfo.datedic objectForKey:editCurrentDate];
        return eventArray;
    }
    NSMutableArray* eventArray = [creatTripInfo.datedic objectForKey:currentDate];
    return eventArray;
}

- (void)setCurrentEvent:(PlaceInfo*)eventInfo
{
    if (isEdit) {
        isEditDataChanged = YES;
        NSMutableArray* eventArray = [editTripInfo.datedic objectForKey:editCurrentDate];
        eventInfo.cityid = [NSString stringWithFormat:@"%@",defaultCityInfo.cityid];
        [eventArray addObject:eventInfo];
        return;
    }
    NSMutableArray* eventArray = [creatTripInfo.datedic objectForKey:currentDate];
    eventInfo.cityid = [NSString stringWithFormat:@"%@",defaultCityInfo.cityid];
    [eventArray addObject:eventInfo];
}

- (void)delCurrentEvent:(PlaceInfo*)eventInfo
{
    if (isEdit) {
        isEditDataChanged = YES;
        NSMutableArray* eventArray = [editTripInfo.datedic objectForKey:editCurrentDate];
        for (PlaceInfo* info in eventArray) {
            if ([info.shopid isEqualToString:eventInfo.shopid]) {
                [eventArray removeObject:info];
                break;
            }
        }
        return;
    }
    NSMutableArray* eventArray = [creatTripInfo.datedic objectForKey:currentDate];
    for (PlaceInfo* info in eventArray) {
        if ([info.shopid isEqualToString:eventInfo.shopid]) {
            [eventArray removeObject:info];
            break;
        }
    }
}

- (NSMutableString*)newTripJSONString
{
    TripInfo* tmpTripinfo;
    if (isEdit) {
        tmpTripinfo = editTripInfo;
    }
    else
    {
        tmpTripinfo= creatTripInfo;
    }
    NSMutableString* jsonString = [[NSMutableString alloc] initWithString:@"{"];
    for (int i = 0; i < [tmpTripinfo.datedic count]; i++) {
        NSArray* sortArray = [[tmpTripinfo.datedic allKeys] sortedArrayUsingFunction:DateSort context:nil];
        NSString* dateString = [sortArray objectAtIndex:i];
        if (i == 0) {
            [jsonString appendString:[NSString stringWithFormat:@"\"%d\":[",i+1]];
        }
        else {
            [jsonString appendString:[NSString stringWithFormat:@",\"%d\":[",i+1]];
        }
        NSArray* eventArray = [tmpTripinfo.datedic objectForKey:dateString];
        for (int k = 0; k < [eventArray count] ; k++) {
            PlaceInfo* placeInfo = [eventArray objectAtIndex:k];
            if (k != 0) {
                [jsonString appendString:[NSString stringWithFormat:@",{\"c_shop_id\":\"%@\",\"c_city_id\":\"%@\",\"type\":\"%@\"}",placeInfo.shopid,placeInfo.cityid,placeInfo.typeid]];
            }
            else {
                [jsonString appendString:[NSString stringWithFormat:@"{\"c_shop_id\":\"%@\",\"c_city_id\":\"%@\",\"type\":\"%@\"}",placeInfo.shopid,placeInfo.cityid,placeInfo.typeid]];
            }
        }
        [jsonString appendString:@"]"];
    }
    [jsonString appendString:@"}"];
    return jsonString;
}

#pragma mark - nouseful
//- (NSMutableString*)DownLoadJSONString:(TripInfo*)info date:(NSString*)startDate
//{
//    BOOL enable = YES;
//    int count = 0;
//    NSMutableString* jsonString = [[NSMutableString alloc] initWithString:@"{"];
//    NSMutableArray* shopinfoArray = [[NSMutableArray alloc] init ];
//    for (int i = 0; i < [info.datedic count]; i++) {
//        NSString* dateString = [[info.datedic allKeys] objectAtIndex:i];
//        
//        NSDate* date = [NSDate dateWithDateString:startDate] ;
//        NSTimeInterval timeInterval = [date timeIntervalSinceReferenceDate];
//        timeInterval += 24*60*60*i;
//        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//        date = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval];
//        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
//        NSString* newDate = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:date]];
//        
//        if (i == 0) {
//            [jsonString appendString:[NSString stringWithFormat:@"\"%@\":{",newDate]];
//        }
//        else {
//            [jsonString appendString:[NSString stringWithFormat:@",\"%@\":{",newDate]];
//        }
//        NSDictionary* datePart = [info.datedic objectForKey:dateString];
//        count = 0;
//        for (int j = 0; j < [datePart count]; j++) {
//            enable = YES;
//            NSString* dataPartString = [[datePart allKeys] objectAtIndex:j];
//            NSMutableDictionary* partInfo = [datePart objectForKey:dataPartString];
//            for (int k = 1; k < 6; k++) {
//                NSMutableArray* placeAry = [partInfo objectForKey:@"list"];
//                [shopinfoArray removeAllObjects];
//                for (NSDictionary* info in placeAry) {
//                    if ([info isKindOfClass:[PlaceInfo class]]) {
//                        [shopinfoArray addObject:info];
//                    }
//                    else if ([[info objectForKey:@"type"] isEqual:[NSString stringWithFormat:@"%d",k]]) {
//                        [shopinfoArray addObject:info];
//                    }
//                }
//                if ([shopinfoArray count] == 0) {
//                    continue;
//                }
//                count ++;
//                if (enable) {
//                    if (count == 1) {
//                        [jsonString appendString:[NSString stringWithFormat:@"\"%d\":{",j+1]];
//                    }
//                    else {
//                        [jsonString appendString:[NSString stringWithFormat:@",\"%d\":{",j+1]];
//                    }
//                    for (CityInfo* info in [[DataSource shareInstance] cityArray]) {
//                        if ([info.name isEqualToString:[partInfo objectForKey:@"city"]]) {
//                            [[DataSource shareInstance] setCityinfoEdit:info];
//                            [jsonString appendString:[NSString stringWithFormat:@"\"c_city_id\":%@",info.cityid]];
//                            break;
//                        }
//                    }
//                    
//                    enable = NO;
//                }
//                [jsonString appendString:[NSString stringWithFormat:@",\"%d\":[",k]];
//                for (int p = 0;p < [placeAry count];p++) {
//                    NSMutableDictionary* placeInfo = [placeAry objectAtIndex:p];
//                    if (p != 0) {
//                        [jsonString appendString:[NSString stringWithFormat:@",{\"c_shop_id\":\"%@\"}",[placeInfo objectForKey:@"c_shop_id"]]];
//                    }
//                    else {
//                        [jsonString appendString:[NSString stringWithFormat:@"{\"c_shop_id\":\"%@\"}",[placeInfo objectForKey:@"c_shop_id"]]];
//                    }
//                }
//                [jsonString appendString:@"]"];
//            }
//            if (enable == NO)
//            {
//                [jsonString appendString:@"}"];
//            }
//        }
//        [jsonString appendString:@"}"];
//    }
//    [jsonString appendString:@"}"];
//    return jsonString;
//}

- (NSMutableString*)JSONString:(TripInfo*)info
{
    return nil;
}
#pragma mark - 城市相关
- (void)setCityList:(NSMutableArray*)cityList
{
    cityArray = [[NSMutableArray alloc] initWithArray:cityList];
}

-(NSMutableArray *)getCityList
{
    if (cityArray && [cityArray count] > 0)
    {
        return cityArray;
    }
    
    [cityArray removeAllObjects];
    return cityArray;
}
@end
